#!/bin/bash
# 检查当前分支是否为master
output1=$(git branch --show-current)
echo "$output1"

if [ "$(git branch --show-current)" != "master" ]; then
    # 如果不是，则检查master分支是否存在
    if git show-ref --quiet refs/heads/master; then
        # 如果存在，则切换到master分支
        git checkout -f master
    else
        # 如果不存在，则创建并切换到master分支
        git checkout -f -b master
    fi
fi
npm -v
output=$(yarn publish:lerna -y --no-push  2>&1)

exit_code=$?

echo "$output"

# 检查退出码
if [ $exit_code -eq 0 ]; then
    echo "All packages published successfully"
    # 解析输出以找出成功发布的包
    # 注意：这里需要根据实际输出调整匹配模式和逻辑
    echo "$output" | awk '/Successfully published:/ {flag=1; next} /lerna success published/ {flag=0} flag' | while read line; do
    # 提取包名和版本号，假设格式为 "Successfully published <package-name>@<version>"
      echo "========="
      echo $line 
      echo "========="
      package_name=$(echo $line | awk '{print $2}' | cut -d'@' -f2)
      version=$(echo $line | awk '{print $2}' | cut -d'@' -f3)
      # 创建 git tag 并推送到远程仓库
      echo "---------"
      echo "$package_name"
      echo "---------"
      echo "*********"
      echo "$version"
      echo "*********"
      output2=$(git tag "$package_name@$version" -m "$package_name@$version")
      echo "$output2"
      output3=$(git push origin master)
      echo "$output3"
      git tag "$package_name@$version" -m "$package_name@$version"
      git push origin master
    done
else
    echo "Some packages may have failed to publish."
  
    # 获取当前分支名称和对应远程跟踪分支名称，并更新远程信息。
    current_branch=$(git rev-parse --abbrev-ref HEAD)
    remote_branch="origin/${current_branch}"
    # 删除所有本地标签
    git tag | xargs git tag -d
    git fetch

    # 检查是否有已commit但尚未推送到远程仓库的更改，并撤销最近一次commit。
    if git log ${remote_branch}..${current_branch} --oneline; then
        echo "存在尚未推送到 ${remote_branch} 的commits，正在撤销最近一次commit..."
        git reset --soft HEAD~1
    else
        echo "没有需要处理的更改。"
    fi
     # 检查是否有暂存但未commit的更改，并撤销它们。
    if ! git diff --cached --quiet; then
        echo "存在尚未commit的暂存文件，正在撤销..."
        git reset HEAD .
    fi
     # 检查工作目录中是否有未提交的修改，并撤销它们。
    if ! git diff --quiet; then
        echo "存在尚未commit的文件修改，正在撤销..."
        git checkout .
    fi
    exit 1
fi










# set -e # Exit immediately if a command exits with a non-zero status.

# output=$(yarn publish:lerna -y --no-push 2>&1)
# echo "$output"

# # 检查退出码
# if [[ $? -eq 0 ]]; then
#     echo "All packages published successfully"
#     # 解析输出以找出成功发布的包
#     echo "$output" | awk '/Successfully published:/ {flag=1; next} /lerna success published/ {flag=0} flag' | while IFS=' ' read -r _ package_info _; do
#         echo "========="
#         echo "$package_info"
#         echo "========="
#         # 提取包名和版本号
#         package_name="${package_info%@}"
#         version="${package_info#@}"
#         # 创建 git tag 并推送到远程仓库
#         git_tag="$package_name@$version"
#         echo "Tagging $git_tag"
#         git tag "$git_tag" -m "$git_tag"
#         git push origin "$git_tag"
#     done
# else
#     echo "Some packages may have failed to publish."

#     # 设置远程仓库名称，默认为origin
#     remote="origin"

#     # 获取所有远程标签并转换为数组
#     readarray -t remote_tags < <(git ls-remote --tags "$remote" | awk '{print $2}' | sed 's/refs\/tags\///' | sort)

#     # 获取所有本地标签并转换为数组
#     readarray -t local_tags < <(git tag | sort)

#     # 比较本地和远程标签，找出只存在于本地的标签
#     tags_to_delete=()
#     for local_tag in "${local_tags[@]}"; do
#         if ! [[ " ${remote_tags[*]} " =~ " ${local_tag} " ]]; then
#             tags_to_delete+=("$local_tag")
#         fi
#     done
#     if [ ${#tags_to_delete[@]} -gt 0 ]; then
#       echo "${tags_to_delete[*]} 本地标签不存在于远程仓库的tag"
#       # 删除这些只存在于本地的标签
#       for tag in "${tags_to_delete[@]}"; do
#           echo "Deleting local tag: $tag"
#           git tag -d "$tag"
#       done
#       echo "Deleting local tag Done."
#       # 发包失败后，删除本地多余的commit（慎用：这可能会丢失数据）
#       git reset --hard HEAD^
#    else
#       echo "No local-only tags found."
#    fi
# fi